<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.LoginName" placeholder="输入名称查询" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="Id" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划ID" align="center">
        <template slot-scope="{row}">
          <span>{{ row.planID }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.planName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="站点组" align="center">
        <template slot-scope="{row}">
          <span>{{ row.siteCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="站点地址" align="center">
        <template slot-scope="{row}">
          <span>{{ row.siteName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="170">
        <template slot-scope="{row,$index}">
          <!-- <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button> -->
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page-sizes="[20]" :page.sync="listQuery.currentPage" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :width="'800px'" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form ref="dataForm" :rules="rules" :inline="true" :model="temp" label-width="120px" style="margin-right:20px">
        <el-form-item label="计划名称">
          <el-select v-model="temp.planName" value-key="planName" :disabled="dialogStatus==='create'?false:true" @change="onTempChange">
            <el-option
              v-for="item in tempOptions"
              :key="item.planName"
              :label="item.planName"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="站点组">
          <el-input v-model="temp.siteCode" />
        </el-form-item>
        <el-form-item label="站点地址">
          <el-input v-model="temp.siteName" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, createArticle, updateArticle, deleteArticle } from '@/api/task-site'
import waves from '@/directive/waves'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'
import { mapGetters } from 'vuex'
import { fetchList as fetchPlanList } from '@/api/task-plan'

const ywTypes = [
  { key: '采集', display_name: '采集' },
  { key: '核查', display_name: '核查' },
]
const dxTypes = [
  { key: '1', display_name: '机房及配套' },
]
const execDurings = [
  { key: '临时', display_name: '临时' },
  { key: '月度', display_name: '月度' },
  { key: '季度', display_name: '季度' },
]

export default {
  name: 'Polling',
  components: { Pagination },
  directives: { waves },
  filters: {},
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        currentPage: 1,
      },
      ywTypes,
      dxTypes,
      execDurings,
      temp: {},
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {
        templateName: [{ required: true, message: '必填项', trigger: 'change' }],
        includeModuleNames: [{ required: true, message: '必填项', trigger: 'change' }],
      },
      format: 'yyyy-MM-dd',
      dates: [],
      tempOptions: []
    }
  },
  computed: {
    ...mapGetters([
      'addressOptions'
    ])
  },
  created() {
    this.getList()
    fetchPlanList().then((res) => {
      this.tempOptions = res.data.records
    })
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {}
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.initDateList()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.planName = this.temp.planName?.planName
          createArticle(this.temp).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.notifyMessage('创建成功')
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let tempData = Object.assign({}, this.temp)
          tempData = { ...tempData, planName: tempData.planName?.planName || tempData.planName }
          updateArticle(tempData).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.notifyMessage('保存成功')
          })
        }
      })
    },
    notifyMessage(info) {
      this.$notify({
        title: info,
        type: 'success',
        duration: 2000
      })
    },
    handleDelete(row, index) {
      deleteArticle({ id: row.id }).then(() => {
        this.getList()
        this.notifyMessage('删除成功')
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    initDateList() {
      const dates = []
      const newDate = new Date()
      const year = newDate.getFullYear()
      const month = newDate.getMonth() + 1
      for (let i = 0; i < 12; i++) {
        let m = month + i
        if (m > 12) {
          m = m - 12
        }
        if (m < 10) {
          m = '0' + m
        }
        dates.push(`${year}-${m}`)
      }
      this.dates = dates
    },
    onTempChange(item) {
      this.temp.planID = item.id
    }
  }
}
</script>
